<!--
  * 客户信息表
  *
  * @Author:    lmabbe
  * @Date:      2025-06-24 14:55:52
  * @Copyright  lmabbe
-->
<template>
  <!---------- 查询表单form begin ----------->
  <div v-privilege="'customerInfo:query'">
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item class="smart-query-form-item" label="关键字查询">
          <a-input v-model:value="queryForm.keywords" placeholder="关键字查询" style="width: 200px" />
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button class="smart-margin-left10" @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card :bordered="false" :hoverable="true" size="small">
      <!---------- 表格操作行 begin ----------->
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button v-privilege="'customerInfo:add'" size="small" type="primary" @click="showForm">
            <template #icon>
              <PlusOutlined />
            </template>
            新建
          </a-button>
          <a-button
            v-privilege="'customerInfo:delete'"
            :disabled="selectedRowKeyList.length == 0"
            danger
            size="small"
            type="primary"
            @click="confirmBatchDelete"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            批量删除
          </a-button>
        </div>
      </a-row>
      <!---------- 表格操作行 end ----------->

      <!---------- 表格 begin ----------->
      <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        :scroll="{ y: 650 }"
        bordered
        rowKey="customerCode"
        size="small"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'contactInformation'">
            <div style="white-space: pre-line">
              <template v-if="text">
                {{
                  JSON.parse(text)
                    .map((item) => `${item.contactName || ''}，${item.contactPhone || ''}，${item.contactPosition || ''}`)
                    .join('\n')
                }}
              </template>
            </div>
          </template>
          <template v-if="column.dataIndex === 'disabledFlag'">
            <a-switch :checked="text" @change="changeDisable(record)" />
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button v-privilege="'customerInfo:setParseBom'" type="link" @click="openBomParseSetting(record)"> BOM模板设置 </a-button>
              <a-button v-privilege="'customerInfo:update'" type="link" @click="showForm(record)">编辑</a-button>
              <a-button v-privilege="'customerInfo:delete'" danger type="link" @click="onDelete(record)">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>
      <!---------- 表格 end ----------->

      <div class="smart-query-table-page">
        <a-pagination
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :defaultPageSize="queryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="queryData"
          @showSizeChange="queryData"
        />
      </div>
    </a-card>
    <CustomerInfoForm ref="formRef" @reloadList="queryData" />
    <bom-template-parse-setting ref="bomParseSetting" />
  </div>
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { customerInfoApi } from '/@/api/business/basic/customer/customer-info-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import CustomerInfoForm from './customer-info-form.vue';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import BomTemplateParseSetting from '/@/views/business/basic/customer/components/bomTemplateParseSetting.vue';

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '客户编号',
      dataIndex: 'customerCode',
      ellipsis: true,
      width: '120px',
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      ellipsis: true,
      width: '160px',
    },
    {
      title: '客户简称',
      dataIndex: 'customerAbbreviation',
      ellipsis: true,
      width: '120px',
    },
    {
      title: '客户地址',
      dataIndex: 'customerAddress',
      ellipsis: true,
      width: '240px',
    },
    {
      title: '联系方式',
      dataIndex: 'contactInformation',
      ellipsis: true,
      width: '240px',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: '240px',
    },
    {
      title: '禁用状态',
      dataIndex: 'disabledFlag',
      ellipsis: true,
      width: '60px',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      ellipsis: true,
      width: '70px',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: '150px',
    },
    {
      title: '更新人',
      dataIndex: 'updateUserName',
      ellipsis: true,
      width: '70px',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      ellipsis: true,
      width: '150px',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 200,
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    keywords: undefined, //关键字查询
    pageNum: 1,
    pageSize: 10,
  };
  // 查询表单form
  const queryForm = reactive({ ...queryFormState });
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await customerInfoApi.queryPage(queryForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  onMounted(queryData);

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref();

  function showForm(data) {
    formRef.value.show(data);
  }

  // ---------------------------- 单个删除 ----------------------------
  //确认删除
  function onDelete(data) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestDelete(data);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求删除
  async function requestDelete(data) {
    SmartLoading.show();
    try {
      let deleteForm = {
        goodsIdList: selectedRowKeyList.value,
      };
      await customerInfoApi.delete(data.customerCode);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([]);

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  // 批量删除
  function confirmBatchDelete() {
    Modal.confirm({
      title: '提示',
      content: '确定要批量删除这些数据吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestBatchDelete();
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求批量删除
  async function requestBatchDelete() {
    try {
      SmartLoading.show();
      await customerInfoApi.batchDelete(selectedRowKeyList.value);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  const bomParseSetting = ref();

  function openBomParseSetting(record) {
    bomParseSetting.value.showModal(record.customerCode);
  }

  function changeDisable(record) {
    customerInfoApi.changeDisable(record.customerCode, !record.disabledFlag).then((res) => {
      record.disabledFlag = !record.disabledFlag;
      message.success('操作成功');
    });
  }
</script>
